package com.jxc.controller.admin;

import com.jxc.entity.admin.Product;
import com.jxc.page.admin.Page;
import com.jxc.service.admin.ProductService;
import com.jxc.service.admin.SupplierService;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 商品
 */
@Controller
@RequestMapping("/admin/product")
public class ProductController {

    @Autowired
    private ProductService productService;
    @Autowired
    private SupplierService supplierService;

    /**
     * 进入供应商查询界面
     */
    @RequestMapping(value="/list",method= RequestMethod.GET)
    public ModelAndView list(ModelAndView model){
        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put("offset", 0);
        queryMap.put("pageSize", 9999);
        model.addObject("supplierList", supplierService.getList(queryMap));
        model.setViewName("product/list");
        return model;
    }

    /**
     * 查询
     */
    @ResponseBody
    @RequestMapping(value = "list",method = RequestMethod.POST)
    public Map<String,Object> add(@RequestParam(value = "content",defaultValue = "") String content
    , Long supplierId ,Page page){
        HashMap<String, Object> map = new HashMap<>();
        map.put("content",content);
        map.put("supplierId",supplierId);
        Integer total = productService.getTotal(map);
        map.put("pageSize",page.getRows());
        map.put("offset",page.getOffset());
        List<Product> products = productService.getList(map);

        HashMap<String, Object> ret = new HashMap<>();
        ret.put("total",total);
        ret.put("rows",products);
        return ret;
    }

    /**
     * 添加一条记录
     */
    @ResponseBody
    @RequestMapping(value = "add",method = RequestMethod.POST)
    public Map<String,String> add(Product product){
        Map<String, String> map = new HashMap<>();
        if(product == null){
            map.put("type","error");
            map.put("msg","该信息为空，请填写再提交");
            return map;
        }
        if(StringUtils.isEmpty(product.getName())){
            map.put("type","error");
            map.put("msg","该商品名称为空，请填写再提交");
            return map;
        }
        if(StringUtils.isEmpty(product.getPk())){
            map.put("type","error");
            map.put("msg","该包装为空，请填写再提交");
            return map;
        }
        if(StringUtils.isEmpty(product.getPlace())){
            map.put("type","error");
            map.put("msg","该商品产地为空，请填写再提交");
            return map;
        }
        if(StringUtils.isEmpty(product.getRemark())){
            map.put("type","error");
            map.put("msg","该商品备注描述为空，请填写再提交");
            return map;
        }
        if(StringUtils.isEmpty(product.getSpec())){
            map.put("type","error");
            map.put("msg","该商品规格为空，请填写再提交");
            return map;
        }
        if(StringUtils.isEmpty(product.getUnit())){
            map.put("type","error");
            map.put("msg","该商品计量单位为空，请填写再提交");
            return map;
        }
        if(StringUtils.isEmpty(product.getPrice().toString())){
            map.put("type","error");
            map.put("msg","该商品价格为空，请填写再提交");
            return map;
        }
        if(productService.add(product) <= 0){
            map.put("type","error");
            map.put("msg","添加失败，请联系管理员");
            return map;
        }
        map.put("type","success");
        map.put("msg","添加成功！！！");
        return map;
    }

    /**
     * 修改一条记录
     */
    @ResponseBody
    @RequestMapping(value = "edit",method = RequestMethod.POST)
    public Map<String,String> edit(Product product){
        Map<String, String> map = new HashMap<>();
        if(product==null){
            map.put("type","error");
            map.put("msg","该信息为空，请填写再提交");
            return map;
        }
        if(StringUtils.isEmpty(product.getName())){
            map.put("type","error");
            map.put("msg","该供应商名称为空，请填写再提交");
            return map;
        }
        if(StringUtils.isEmpty(product.getPk())){
            map.put("type","error");
            map.put("msg","该包装为空，请填写再提交");
            return map;
        }
        if(StringUtils.isEmpty(product.getPlace())){
            map.put("type","error");
            map.put("msg","该商品产地为空，请填写再提交");
            return map;
        }
        if(StringUtils.isEmpty(product.getRemark())){
            map.put("type","error");
            map.put("msg","该商品备注描述为空，请填写再提交");
            return map;
        }
        if(StringUtils.isEmpty(product.getSpec())){
            map.put("type","error");
            map.put("msg","该商品规格为空，请填写再提交");
            return map;
        }
        if(StringUtils.isEmpty(product.getUnit())){
            map.put("type","error");
            map.put("msg","该商品计量单位为空，请填写再提交");
            return map;
        }
        if(StringUtils.isEmpty(product.getPrice().toString())){
            map.put("type","error");
            map.put("msg","该商品价格为空，请填写再提交");
            return map;
        }
        if(productService.edit(product) <= 0){
            map.put("type","error");
            map.put("msg","修改失败，请联系管理员");
            return map;
        }
        map.put("type","success");
        map.put("msg","修改成功！！！");
        return map;
    }

    /**
     * 删除
     */
    @RequestMapping(value="delete",method=RequestMethod.POST)
    @ResponseBody
    public Map<String, String> delete(@RequestParam(value = "ids") String ids){
        Map<String, String> ret = new HashMap<>();
        if(StringUtils.isEmpty(ids)){
            ret.put("type", "error");
            ret.put("msg", "选择要删除的数据！");
            return ret;
        }
        if(ids.contains(",")){
            ids = ids.substring(0,ids.length()-1);
        }
        if(productService.deleteByIds(ids) <= 0){
            ret.put("type", "error");
            ret.put("msg", "删除失败，请联系管理员！");
            return ret;
        }
        ret.put("type", "success");
        ret.put("msg", "删除成功！");
        return ret;
    }

    /**
     * 导入商品
     */
    @RequestMapping(value="import_product",method=RequestMethod.POST)
    @ResponseBody
    public Map<String, String> importFile(MultipartFile excelFile, Long supplierId){
        Map<String, String> ret = new HashMap<>();
        if(supplierId == null){
            ret.put("type", "error");
            ret.put("msg", "请选择供应商!");
            return ret;
        }
        if(excelFile == null){
            ret.put("type", "error");
            ret.put("msg", "请选择上传的文件!");
            return ret;
        }
        if(excelFile.getSize() > 5000000){
            ret.put("type", "error");
            ret.put("msg", "文件大小超过5M,请上传不大于5M的文件");
            return ret;
        }
        //获取文件后缀
        String suffix = excelFile.getOriginalFilename().substring(excelFile.getOriginalFilename().lastIndexOf(".")+1,excelFile.getOriginalFilename().length());
        if(!"xlsx,xls".contains(suffix)){
            ret.put("type", "error");
            ret.put("msg", "请上传xlsx或xls格式的文件!");
            return ret;
        }
        String msg = "";
        try {
            msg = addProductByFile(supplierId,excelFile.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        if("".equals(msg)){
            msg = "全部导入成功";
        }
        try {
            ret.put("type", "success");
            ret.put("msg", new String(msg.getBytes("gbk"),"utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return ret;
    }

    private String addProductByFile(Long supplierId, InputStream inputStream){
        String msg = "";
        try {
            HSSFWorkbook hssfWorkbook = new HSSFWorkbook(inputStream);
            HSSFSheet sheetAt = hssfWorkbook.getSheetAt(0);
            //去掉表头，送第二行开始读
            if(sheetAt.getLastRowNum() <= 0){
                msg = "文件内容为空!";
            }
            System.out.println(sheetAt.getLastRowNum());
            for(int rowIndex = 1; rowIndex <= sheetAt.getLastRowNum(); rowIndex++){
                HSSFRow row = sheetAt.getRow(rowIndex);
                Product product = new Product();
                if(row.getCell(0) == null){
                    msg += "第" + (rowIndex+1) + "行商品名称为空，跳过!\n";
                    continue;
                }
                String name = row.getCell(0).getStringCellValue();
                product.setName(name);
                product.setPlace(row.getCell(1) == null ? "" : row.getCell(1).getStringCellValue());
                product.setSpec(row.getCell(2) == null ? "" : row.getCell(2).getStringCellValue());
                product.setPk(row.getCell(3) == null ? "" : row.getCell(3).getStringCellValue());
                product.setUnit(row.getCell(4) == null ? "" : row.getCell(4).getStringCellValue());

                if(row.getCell(5) == null){
                    msg += "第" + (rowIndex+1) + "行商品价格为空，跳过!\n";
                    continue;
                }

                try {
                    Double priceDouble = row.getCell(5).getNumericCellValue();
                    float price = Float.valueOf(priceDouble+"");
                    product.setPrice(price);
                } catch (Exception e) {
                    msg += "第" + (rowIndex+1) + "行商品价格格式错误，跳过!\n";
                    continue;
                }
                product.setRemark(row.getCell(6) == null ? "" : row.getCell(6).getStringCellValue());

                product.setSupplierId(supplierId);
                if(productService.add(product) <= 0){
                    msg += "第" + (rowIndex+1) + "行商品添加失败!\n";
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return msg;
    }

}
